<?php


namespace app\api\model;

use app\api\service\Bank;
use app\common\exception\BaseException;
use app\common\model\Region;
use app\common\model\UserChannel as UserChannelModel;
class UserChannel extends UserChannelModel
{
    /**
     * 写入user_channel表
     * @param $param
     * @return bool|mixed
     */
    public function insertData($param){
        $region_str = Region::getMergerName($param['region_id']);
        $region = explode(',', $region_str);
        $province_id = Region::getIdByName($region[1], 1);
        $city_id = Region::getIdByName($region[2], 2, $province_id);
        $data = [
            'user_id' => $param['user_id'],
            'channel_id' => $param['channel_id'],
            'merchantno' => '',
            'realname' => $param['name'],
            'certno' => $param['idno'],
            'bankname' => $param['acctbankname'],
            'bankno' => $param['bankcode'],
            'accno' => $param['acctid'],
            'rate' => $param['rate'],
            'advancefee' => $param['advancefee'],
            'phoneno' => $param['mobile'],
            'province_id' => $province_id,
            'city_id' => $city_id,
            'notes' => '',
            'status' => 0,
            'wxapp_id' => self::$wxapp_id,
        ];
        return $this->save($data)?$this->id:false;
    }

    /**
     * 判断当前用户对应渠道是否已注册激活
     * @param $user_id
     * @param $channel_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function checkUserChannel($user_id,$channel_id){
        $model = (new static());
        $filter = [
            'user_id' => $user_id,
            'channel_id' => $channel_id,
            'wxapp_id' => self::$wxapp_id,
        ];
        return  ($model->where($filter)->find())?true:false;
    }

    /**
     * 修改费率
     * @param $param
     */
    public function changerate($param){
        $this->startTrans();
        try {
            $bank = new Bank();
            $bank->changerate($param);
            $this->commit();
        }catch (\Exception $e) {
            $this->rollback();
            throw new BaseException(['msg' => $e->getMessage()]);
        }
        return true;
    }
}